<template>
  <div
    class="component-mobile-videos__player"
    id="videos__player"
    :style="{ height: is_mobile ? '4rem' : '472px' }"
  >
    <div
      id="videoPlayer"
      :class="[
        'video-player-box',
        isGLSourse ? (is_mobile ? 'gelin-player' : 'gelin-player-pc') : null
      ]"
      ref="video-box"
      v-if="is_reloaded"
    >
    <div class="bullet-screen" id="bullet-screen">{{bulletName}}</div>
    </div>
    <!-- <div class="bullet-screen" id="bullet-screen">跑马灯</div> -->
  </div>
</template>

<script>
import Lang from "./xgplayLang";
import { mapState, mapActions, mapMutations } from "vuex";
import { getVideoUrl } from "~/api/course";
export default {
  props: [
    "sources",
    "timeUpdate",
    "startTime",
    "chapter_obj",
    "updateLastStudyTime",
    "isJump",
  ],
  components: {},
  data() {
    return {
      player: null,
      player_dom: null, //事件监听对象
      retry_count: 0,
      is_reloaded: true, //组件刷新开关
      is_reload_video: false, //重载视频信引
      last_drag_play_time: 0, //拖拽进度条前时长记录
      last_drag_origin_time: 0, //拖拽回退的原始时长
      isDone:false,//是否禁止播放
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      locale(state) {
        return state.locale;
      },
      is_mobile(state) {
        return state.is_mobile;
      },
      is_ios(state) {
        return state.is_ios;
      },
      web_info(state) {
        return state.web_info;
      },
      is_in_minigram(state) {
        return state.is_in_minigram;
      },
      KLGL: state => state.kl_md.KLGL
    }),
    isGLSourse() {
      return /aiapp.koo6.cn/.test(this.sources);
    },
    bulletName(){
      return this.user_info.account + "正在观看视频";
    }
  },
  watch: {
    sources: {
      handler(new_val, old_val) {
        this.destroyPlayer(() => {
          if (new_val && new_val != old_val) {
            // if (this.getVideoType(new_val) !== this.getVideoType(old_val)) {
            //   console.warn("开始重置H5视频播放器");
            //   this.destroyPlayer();
            //   this.retry_count = 0;
            //   this.initPlayer();
            //   // this.is_reload_video = true;
            // } else {
            //   this.player && this.player.reload();
            //   this.is_reload_video = true;
            //   // console.log("player更新:", this.player);
            // }
            // console.log("new_val:", new_val);
            // console.log("old_val:", old_val);
            this.$nextTick(() => {
              this.retry_count = 0;
              this.is_reload_video = true;
              this.initPlayer();
            });
          }
        });
      },
      deep: true,
      immediate: true
    },
    startTime(new_val, old_val) {
      console.log("上次播放new_val:", new_val);
      console.log("上次播放old_val:", old_val);
      // this.destroyPlayer();
      if (new_val != old_val) {
        this.destroyPlayer(() => {
          this.$nextTick(() => {
            this.retry_count = 0;
            this.is_reload_video = true;
            this.initPlayer();
            if (this.player_dom) {
              this.last_drag_play_time = new_val;
              this.player_dom.currentTime = new_val;
            }
          });
        });
      }
    }
  },
  activated() {
    if (process.client) {
      this.initPlayer();
    }
  },
  deactivated() {
    this.destroyPlayer();
    if (this.player_dom) {
      this.player_dom.removeEventListener("timeupdate", this.onPlaying);
      this.player_dom = null;
    }
    // this.player = null;
  },
  destroyed() {
    this.destroyPlayer();
    if (this.player_dom) {
      this.player_dom.removeEventListener("timeupdate", this.onPlaying);
      this.player_dom = null;
    }
    // this.player = null;
  },
  methods: {
    initBullet(){
      let bulletDom = document.getElementById('bullet-screen');
      let videoDom = document.getElementById('videoPlayer');
      if(bulletDom && videoDom){
        let top = Math.floor(((videoDom.offsetHeight - 40) * Math.random()) + 20);
        bulletDom.style.top = top + 'px';
        // 动画重复运动时事件
        bulletDom.addEventListener("webkitAnimationIteration", function() {
          // let videoDom = document.getElementById('videoPlayer');
          let newTop = Math.floor(((videoDom.offsetHeight - 40) * Math.random()) + 20);
          bulletDom.style.top = newTop + 'px';
        })
        bulletDom.addEventListener("animationiteration", function() {
          // let videoDom = document.getElementById('videoPlayer');
          let newTop = Math.floor(((videoDom.offsetHeight - 40) * Math.random()) + 20);
          bulletDom.style.top = newTop + 'px';
        })
      }
    },
    async initPlayer() {
      // this.destroyPlayer();
      if(this.web_info.VIDEO_BULLET == 1){
        this.initBullet();
      }
      try {
        console.log(this.sources);
        let json_result = JSON.parse(this.sources);
        if (json_result.glUrl) {
          let result = await getVideoUrl(json_result.glUrl)
            .then()
            .catch(e => {
              console.log(e);
            });
          console.log("视频解析后的地址：", result);
          this.$emit("setSources", result.data);

          // this.sources = result.data;
          return;
        }
      } catch (e) {
        // console.log("解析错误：", e);
      }
      const HlsPlayer = require("xgplayer-hls.js");
      const FlvPlayer = require("xgplayer-flv");
      const Player = require("xgplayer");

      let videoPlayer = document.querySelector("#videoPlayer");
      if (!this.sources || !videoPlayer) {
        this.retry_count++;
        if (this.retry_count < 4) {
          setTimeout(() => {
            this.initPlayer();
          }, 500);
          return;
        }
        return;
      } else {
        console.log(
          "video ====================:",
          document.getElementsByTagName("video")
        );
        if (
          document.getElementsByTagName("video").length > 0 ||
          this.player !== null
        ) {
          return;
        }

        let i18n = function() {
          let player = this;
          let lang = Lang;
          let util = player.constructor.util;

          Object.defineProperty(player, "lang", {
            get: function() {
              if (player.config) {
                return lang[player.config.lang] || lang["en"];
              } else {
                return lang["en"];
              }
            },
            set: function(value) {
              if (util.typeOf(value) === "Object") {
                Object.keys(value).forEach(key => {
                  lang[key] = value[key];
                });
              }
            }
          });
        };

        if (/\.m3u8/i.test(this.sources)) {
          console.log("==========hls直播==========");
          HlsPlayer.install("i18n", i18n);
          let loading = function(player) {
            // 插件逻辑
            // console.log("player:", player);
          };
          HlsPlayer.install("loading", loading);
          let hls_param = {
            id: "videoPlayer",
            url: this.sources,
            isLive: false,
            volume: 0.5,
            preloadTime: 15,
            minCachedTime: 10,
            autoplay: true,
            videoInit: true,
            fluid: true,
            playsinline: true,
            closeVideoClick: true,
            closeVideoTouch: true,
            lang: this.locale,
            "x5-video-orientation": "portraint"
          };
          if (this.chapter_obj && this.chapter_obj.isLive) {
            hls_param = {
              ...hls_param,
              isLive: true,
              ignores: ["time"]
            };
          } else {
            hls_param = {
              ...hls_param,
              playbackRate: [0.7, 1, 1.5, 2],
              keyShortcut: "on"
            };
          }
          console.log("hls_param:", hls_param);
          this.player = new HlsPlayer(hls_param);
        } else if (/\.flv/i.test(this.sources)) {
          console.log("==========flv直播==========");
          FlvPlayer.install("i18n", i18n);
          let flv_param = {
            id: "videoPlayer",
            url: this.sources,
            isLive: false,
            volume: 0.5,
            preloadTime: 15,
            minCachedTime: 10,
            autoplay: true,
            videoInit: true,
            fluid: true,
            playsinline: true,
            closeVideoClick: true,
            closeVideoTouch: true,
            lang: this.locale,
            "x5-video-orientation": "portraint"
          };
          if (this.chapter_obj && this.chapter_obj.isLive) {
            flv_param = {
              ...flv_param,
              isLive: true,
              ignores: ["time"]
            };
          } else {
            flv_param = {
              ...flv_param,
              playbackRate: [0.7, 1, 1.5, 2],
              keyShortcut: "on"
            };
          }
          this.player = new FlvPlayer(flv_param);
        } else if (/\.mp4/i.test(this.sources)) {
          console.log("==========视频播放==========");
          Player.install("i18n", i18n);
          this.player = new Player({
            id: "videoPlayer",
            url: this.sources,
            volume: 0.5,
            preloadTime: 15,
            autoplay: true,
            videoInit: true,
            playbackRate: [0.7, 1, 1.5, 2],
            fluid: true,
            playsinline: true,
            closeVideoClick: true,
            closeVideoTouch: true,
            lang: this.locale,
            // cssFullscreen: true,
            // "x5-video-player-type": "h5",
            // "x5-video-player-fullscreen": false,
            "x5-video-orientation": "portraint",
            keyShortcut: "on"
          });
          console.log("this.player:", this.player);
          this.player_dom = document.querySelector("#videoPlayer > video");
          if (this.player_dom) {
            this.player_dom.addEventListener("timeupdate", this.onPlaying);
            this.player_dom.currentTime = this.startTime;
          }
        } else {
          console.log("==========其他格式尝试播放==========");
          Player.install("i18n", i18n);
          this.player = new Player({
            id: "videoPlayer",
            url: this.sources,
            volume: 0.5,
            preloadTime: 15,
            autoplay: true,
            videoInit: true,
            playbackRate: [0.7, 1, 1.5, 2],
            fluid: true,
            playsinline: true,
            closeVideoClick: true,
            closeVideoTouch: true,
            lang: this.locale,
            // cssFullscreen: true,
            // "x5-video-player-type": "h5",
            // "x5-video-player-fullscreen": false,
            "x5-video-orientation": "portraint",
            keyShortcut: "on"
          });
          console.log("this.player:", this.player);
          this.player_dom = document.querySelector("#videoPlayer > video");
          if (this.player_dom) {
            this.player_dom.addEventListener("timeupdate", this.onPlaying);
            this.player_dom.currentTime = this.startTime;
          }
        }
        this.player.on("complete", () => {
          console.log("complete");
          //重载视频暂停
          console.log(this.player);
          if (this.is_reload_video) {
            if (!this.player.paused) {
              this.player && this.player.pause();
            }
            this.is_reload_video = false;
          }
        });
        this.player.on("destroy", () => {
          console.log("destroy");
          console.log("play:", this.player);
          // this.player && this.player.reload();
        });
        this.player.on("error", (e) => {
          console.log("error",e);
          this.destroyPlayer(()=>{
            this.initPlayer();
          });
        });
        this.player.on("ended", () => {
          console.log("ended");
          this.updateLastStudyTime();
        });
        this.player.on("playing", () => {
          console.log("playing");
          
          //重载视频暂停
          console.log(this.player);
          if (this.is_reload_video) {
            if (!this.player.paused) {
              this.player && this.player.pause();
            }
            this.is_reload_video = false;
          }
        });
        this.player.on("play", (e) => {
          console.log("play",e);
          // console.log(bulletDom);
          if(this.web_info.VIDEO_BULLET == 1){
            let bulletDom = document.getElementById('bullet-screen');
            bulletDom.style.animationPlayState = "running";
          }
          this.IOSBugCheckOnWeChatMinigram();
        });
        this.player.on("canplay", this.canplay);
        this.player.on("waiting", e => {
          console.log("waiting");
          console.log(e);
          // setTimeout(() => {
          //   console.log("重新加载");
          //   this.player.emit("error");
          // }, 30000);
        });
        this.player.on("seeking", () => {
          console.log("seeking");
        });
        this.player.on("seeked", () => {
          console.log("seeked");
        });
        this.player.on("pause", () => {
          console.log("pause");
          if(this.web_info.VIDEO_BULLET == 1){
            let bulletDom = document.getElementById('bullet-screen');
            bulletDom.style.animationPlayState = "paused";
          }
          this.IOSBugCheckOnWeChatMinigram();
        });
        // this.player.on("error", (e) => {
        //   console.log("error",e);
        // });
        this.player.on("requestFullscreen", () => {
          console.log("进入全屏");
          console.log("font-size:", originFontSize, currentFontSize);
        });
        this.player.on("exitFullscreen", () => {
          console.log("退出全屏");
          console.log("font-size:", originFontSize, currentFontSize);
        });
        window.addEventListener(
          "orientationchange",
          this.IOSBugCheckOnWeChatMinigram,
          false
        );
        console.log("this.player:", this.player);
      }
    },
    canplay() {
      // //ios拖拽进度条设置进度时长
      // if (this.is_ios) {
      //   this.player_dom.currentTime = Math.floor(this.last_drag_play_time);
      // }
      if (this.is_reload_video) {
        if (!this.player.paused) {
          this.player && this.player.pause();
        }
        this.is_reload_video = false;
      }
    },
    onPlaying(e) {
      if(this.web_info.VIDEO_BULLET == 1){
        let bulletDom = document.getElementById('bullet-screen');
        let videoDom = document.getElementById('videoPlayer');
        if(!bulletDom){
          let top = Math.floor(((videoDom.offsetHeight - 40) * Math.random()) + 20);
          let div = document.createElement('div');
          div.setAttribute('class','bullet-screen');
          div.setAttribute('id','bullet-screen');
          let text = document.createTextNode(this.bulletName);
          div.appendChild(text);
          div.style.top = top + 'px';
          div.style.animationPlayState = 'running'
          videoDom.appendChild(div);
          this.initBullet();
        }
      }
      // console.log("currentTime:", this.player_dom.currentTime);
      // 处理试看指定时长
      // if(this.player_dom.currentTime > 30 && this.isJump){
      //   if (!this.player.paused) {
      //     this.player && this.player.pause();
      //     alert("试看完成")
      //   }
      // }
      // console.log("e:", e);

      //禁止拖动进度条
      // const { currentTime } = this.player_dom;
      // if (currentTime) {
      //   //快进
      //   if (currentTime > this.last_drag_play_time) {
      //     console.log("快进");
      //     //快进小于一秒正常播放
      //     if (
      //       currentTime - this.last_drag_play_time < 1 ||
      //       currentTime <= this.last_drag_origin_time
      //     ) {
      //       console.log("正常播放");
      //       this.last_drag_play_time = currentTime;
      //     } else {
      //       console.log("重载进度条");
      //       this.player_dom.currentTime = this.last_drag_play_time;
      //     }
      //     //快退
      //   }
      //   // else if (currentTime < this.last_drag_play_time) {
      //   //   console.log("快退");
      //   //   // this.last_drag_origin_time = currentTime;
      //   //   this.player_dom.currentTime = Math.floor(this.last_drag_play_time);
      //   // }
      // }
      this.timeUpdate && this.timeUpdate(this.player_dom.currentTime);
    },
    destroyPlayer(callback) {
      try {
        this.player && this.player.destroy && this.player.destroy(true);
        let video_box = document.getElementById("videoPlayer");
        video_box && (video_box.className = "video-player-box");
        video_box.innerHTML = "";
        this.player = null;
      } catch (e) {
        console.log(e);
        let video_box = document.getElementById("videoPlayer");
        video_box && (video_box.className = "video-player-box");
        video_box && (video_box.innerHTML = "");
        this.player = null;
      }
      window.removeEventListener(
        "orientationchange",
        this.IOSBugCheckOnWeChatMinigram
      );
      this.is_reloaded = false;
      this.$nextTick(() => {
        this.is_reloaded = true;
        callback && callback();
      });
    },
    getVideoType(str) {
      if (str) {
        let match_result = str.match(/\.[^\.]+$/i);
        if (match_result.length > 0) {
          match_result = match_result[0].replace(/\?.+$/, "");
          // console.log("match_result:", match_result);
          return match_result;
        } else {
          return new Date().getTime();
        }
      } else {
        return new Date().getTime();
      }
    },
    IOSBugCheckOnWeChatMinigram() {
      if (this.is_ios && this.is_in_minigram) {
        document.getElementsByTagName("html")[0].style.fontSize =
          originFontSize + "px";
      }
    }
  },
  created() {},
  mounted() {
    this.$nextTick(() => {
      if (process.client) {
        this.initPlayer();
      }
    });
  }
};
</script>

<style lang="scss">
.component-mobile-videos__player {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #000;
  position: relative;
  .bullet-screen{
    position: absolute;
    top: 100px;
    color: #fff;
    font-size: 16px;
    white-space: nowrap;
    animation: bullet 10s linear infinite;
    animation-play-state: paused;
    opacity: .5;
  }
  @keyframes bullet{
    0%{
      left:100%
    }
    to{
      left:0;
      transform:translateX(-100%)
    }
  }
  .play-icon {
    font-size: 0.8rem;
  }
  .video-player-box {
    width: 7.2rem !important;
    height: 100% !important;
    overflow: hidden;
    .video-js {
      font-size: 0.16rem;
      .vjs-big-play-button {
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }
    .vjs-error .vjs-error-display:before {
      display: none;
    }
    .vjs-modal-dialog .vjs-modal-dialog-content {
      padding: 0.3rem 0.4rem;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #000;
    }
  }
  .error_log {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    color: #fff;
    font-size: 0.24rem;
  }

  .gelin-player {
    > video {
      width: 7.92rem !important;
      height: 4.4rem !important;
      top: unset !important;
      left: unset !important;
      right: -0.05rem !important;
      bottom: 0 !important;
    }
  }
  .gelin-player-pc {
    > video {
      width: 108% !important;
      height: 108% !important;
      top: unset !important;
      left: unset !important;
      right: -6px !important;
      bottom: 0 !important;
    }
  }
}
</style>
